package com.stormragetech.teamwork.spring.interceptor;

import com.stormragetech.teamwork.common.constant.Constants;
import com.stormragetech.teamwork.common.util.AESCrypt;
import com.stormragetech.teamwork.module.user.spring.redis.RedisDao;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Log4j2
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${aeskey}")
    private String aeskey;

    private final RedisDao redisDao;

    @Autowired
    public LoginInterceptor(RedisDao redisDao) {
        Assert.notNull(redisDao, "RedisDao cannot be null !!!");
        this.redisDao = redisDao;
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println();
        log.info("------      登录拦截器开始      ------");
        log.info("------      请求地址: {}      ", request.getServletPath());
        log.info("aeskey is: {}", aeskey);

        // 获取cookie中登录token
        // Cookie为空
        // 返回登录页面
        //
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length <= 0) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "cookie为空，返回登录");
            log.info("------      登录拦截器结束      ------");
            return false;
        }

        String token = null;
        for (Cookie cookie : cookies) {
            if (Constants.COOKIE_NAME.equals(cookie.getName())) {
                token = cookie.getValue();
                break;
            }
        }

        // cookie中为含有token
        // 返回登录页面
        //
        if (null == token) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "cookie不含token，返回登录");
            log.info("------      登录拦截器结束      ------");
            return false;
        }

        // redis中未含有登录token
        // 返回登录页面
        //
        token = AESCrypt.decrypt(token, aeskey);
        String id = redisDao.getKey(token);
        if (null == id || id.length() <= 0) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "redis不含token，返回登录");
            log.info("------      登录拦截器结束      ------");
            return false;
        }

        // 登录验证成功
        //
        log.info("------      验证结果: {}      ", "通过");
        log.info("------      登录拦截器结束      ------");
        return true;

    }
}
